import 'package:decimal/decimal.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/team_model.dart';
import 'package:wu_you/page/ad/page_reward_video.dart';
import 'package:wu_you/page/user/page_funds_list.dart';
import 'package:wu_you/page/user/page_points_market.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/http_status_widget.dart';

///市场
class MarketPage extends StatefulWidget{
  @override
  MarketPageState createState() => MarketPageState();
}
class MarketPageState extends State<MarketPage>{
  List<String> _tabs = [];
  @override
  void initState() {
    super.initState();
  }

  var message;
  int _index = 0;
  BuildContext ctx;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    double width = MediaQuery.of(context).size.width;
    _tabs.clear();
    _tabs = ['${message['dealer']}','${message['member']}'];
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
          appBar: AppBar(
            title: Text("${message['tabMarket']}"),
          ),
          backgroundColor: HexColor('#F8F8F8'),
          body: HttpWidget<TeamInfoModel, TeamInfoBloc>(
              create: (context) => TeamInfoBloc()..add(HttpEvent()),
              child: (context, data) {
                ctx = context;
                return RefreshIndicator(
                  notificationPredicate: (notifation) {
                    // 返回true即可,避免下拉刷新时和NestedScrollView滑动冲突
                    return true;
                  },
                  onRefresh: (){
                    BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
                    return Future.value(true);
                  },
                  child: NestedScrollView(
                      headerSliverBuilder: (context, h) {
                        return[
                          SliverToBoxAdapter(
                            child: Stack(
                              children: [
                                AspectRatio(
                                  aspectRatio: 2.9,
                                  child: Container(
                                    decoration: BoxDecoration(
                                        color: AppColors.primaryColor
                                    ),
                                  ),
                                ),
                                Container(
                                    padding: EdgeInsets.only(top: 15),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          // mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: [
                                            Expanded(
                                              child: Container(
                                                child: _buildTopView("${message['Bonuspool']}", '${Decimal.parse(data.reward.ach).toString()}'),
                                                alignment: Alignment.center,
                                                padding: EdgeInsets.all(2),
                                              )
                                            ),
                                            Expanded(
                                              child: Container(
                                                child: _buildTopView("${message['turnover']}", '${Utils.formatLuckCharCount(double.parse(data.reward.sach).round())}'),
                                                alignment: Alignment.center,
                                                padding: EdgeInsets.all(2),
                                              )
                                            ),
                                            Expanded(
                                              child: Container(
                                                child: _buildTopView("${message['fhjs']}", '${Decimal.parse("${data.reward.capping}").toString()}'),
                                                alignment: Alignment.center,
                                                padding: EdgeInsets.all(2),
                                              ).addGesture(() {
                                                NavigatorUtil.navigateToPage(context, PointsMarketPage());
                                              })
                                            ),
                                          ],
                                        ),
                                        SizedBox(height: 15,),
                                        Container(
                                            width: double.infinity,
                                            height: 120,
                                            padding: EdgeInsets.only(left: 15,right: 15,top: 13,bottom: 8),
                                            margin: EdgeInsets.only(left: 12,right: 12,bottom: 6),
                                            decoration: BoxDecoration(
                                                boxShadow: [BoxShadow(color: HexColor("#DCDCDC"), blurRadius: 8.0)],
                                                borderRadius: BorderRadius.all(Radius.circular(8)),
                                                color: Colors.white
                                            ),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Text("${message['Myearnings']}",style: TextStyle(fontSize: 17,fontWeight: FontWeight.bold),),
                                                SizedBox(height: 15,),
                                                Row(
                                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                  children: [
                                                    _buildRowLabel('${message['commission']}','${Decimal.parse("${data.reward.push_reward}").toString()}',"10","${message['user16']}"),
                                                    _buildRowLabel('${message['Prizedraw']}','${Decimal.parse("${data.reward.share_rewards}").toString()}',"11","${message['user17']}"),
                                                    _buildRowLabel('${message['abonus']}','${Decimal.parse("${data.reward.peer_reward}").toString()}',"12","${message['user18']}"),
                                                  ],
                                                ),
                                                SizedBox(height: 6,),
                                                // Row(
                                                //   mainAxisAlignment: MainAxisAlignment.end,
                                                //   children: [
                                                //     Text("${message['receive']}",style: TextStyle(fontSize: 13,color: AppColors.primaryColor,decoration: TextDecoration.underline),).addGesture(() {
                                                //       LoadingApi.func(UserRepository().getTeamReward(), context,complete: (v){
                                                //         ToastUtils.show("${message['Success']}", context);
                                                //         BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
                                                //       },error: (e){
                                                //         ToastUtils.show("$e", context);
                                                //       });
                                                //     })
                                                //   ],
                                                // )
                                              ],
                                            )
                                        )
                                      ],
                                    )
                                ),
                              ],
                            ),
                          ),
                          SliverPersistentHeader(
                              pinned: true,
                              delegate: StickyTabBarDelegate(
                                child:
                                TabBar(
                                    isScrollable: true,
                                    labelColor: AppColors.authSelectedLabelColor,
                                    // indicatorColor: AppColors.dividerColor,
                                    unselectedLabelColor: AppColors.textHintColor,
                                    indicatorSize: TabBarIndicatorSize.label,
                                    indicator: const BoxDecoration(),
                                    labelStyle: TextStyle(fontSize: 15),
                                    onTap: (index){
                                      setState(() {
                                        _index = index;
                                      });
                                    },
                                    tabs: [
                                      Tab(
                                        child: Container(
                                          padding: EdgeInsets.only(left: 12,right: 12,top: 5,bottom: 5),
                                          decoration: _index == 0
                                              ? BoxDecoration(
                                              borderRadius: BorderRadius.circular(8), color: AppColors.primaryColor)
                                              : BoxDecoration(borderRadius: BorderRadius.circular(8),border: Border.all(color: HexColor("#BEBEBE"),width: 1)),
                                          child: Text(_tabs[0]),
                                        ),
                                      ),
                                      Tab(
                                        child: Container(
                                          padding: EdgeInsets.only(left: 12,right: 12,top: 5,bottom: 5),
                                          decoration: _index == 1
                                              ? BoxDecoration(
                                              borderRadius: BorderRadius.circular(8), color: AppColors.primaryColor)
                                              : BoxDecoration(borderRadius: BorderRadius.circular(8),border: Border.all(color: HexColor("#BEBEBE"),width: 1)),
                                          child: Text(_tabs[1]),
                                        ),
                                      ),
                                    ]
                                ),
                              )
                          )
                        ];
                      },
                      body: TabBarView(
                          physics: NeverScrollableScrollPhysics(),
                          children: [
                            buildTableViewItemWidget(data.dealer),
                            buildTableViewItemWidget(data.enroll),
                          ]
                      )
                  ),
                );
              }
          )
        )
    );
  }


  Widget buildTableViewItemWidget(List<TeamUserList> list){
    if(list != null && list.length != 0){
      return ListView.builder(
        itemBuilder: (context,index){
          TeamUserList item = list[index];
          return Container(
            margin: EdgeInsets.only(top: 6,left: 12,right: 12),
            padding: EdgeInsets.all(12),
            decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              borderRadius: BorderRadius.all(Radius.circular(10)),
              color: Colors.white,
              border: Border.all(
                color: HexColor("#F7F7F7"),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Image.network("${item.head}",width: 50,height: 50,fit: BoxFit.fill,errorBuilder: (context,err,stackTrace){
                    return Image.asset(Utils.getImgPath('ic_logo'),width: 50,height: 50,);
                  },),
                ),
                SizedBox(width: 12,),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text("${item.username}",style: TextStyle(color: AppColors.textHintColor),),
                    SizedBox(height: 2,),
                    RichText(
                        textAlign: TextAlign.start,
                        text: TextSpan(style: TextStyle(color: AppColors.textHintColor,fontSize: 13),
                            children: [
                              TextSpan(text: "${message['turnover']}："),
                              TextSpan(text: "${item.sach}",style: TextStyle(color: AppColors.textColor)),
                            ]
                        )
                    ),
                    // RichText(
                    //     textAlign: TextAlign.start,
                    //     text: TextSpan(style: TextStyle(color: AppColors.textHintColor,fontSize: 13),
                    //         children: [
                    //           TextSpan(text: "${message['CappingZ']}："),
                    //           TextSpan(text: "${item.capping}",style: TextStyle(color: AppColors.textColor)),
                    //         ]
                    //     )
                    // ),
                  ],
                )
              ],
            ),
          );
        },
        itemCount: list.length,
      );
    }else{
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(Utils.getImgPath('ic_empty'),width: 66,height: 66,),
            SizedBox(height: 10,),
            Text("${message['noData']}", style: TextStyle(color: AppColors.textHintColor, fontSize: 13),),
          ],
        )
      );
    }
  }


  Widget _buildRowLabel(String label,String num,String type,String title){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(label,style: TextStyle(fontSize: 13,color: AppColors.textHintColor),),
                Image.asset(Utils.getImgPath('ic_user_wenhao'),width: 15,height: 15,color: AppColors.textHintColor,)
              ],
            ),
            SizedBox(height: 6,),
            Text(num,style: TextStyle(fontSize: 16,color: AppColors.textColor,fontWeight: FontWeight.bold),),
          ],
        ).addGesture(() {
          NavigatorUtil.navigateToPage(context, FundsListPage(type: type, title:title));
        }),
        // SizedBox(height: 10,),
        // Text("${message['receive']}",style: TextStyle(fontSize: 13,color: AppColors.primaryColor,decoration: TextDecoration.underline),).addGesture(() {
        //   if(type == "10"){
        //     LoadingApi.func(UserRepository().getSaleReward(), context,complete: (v){
        //       ToastUtils.show("$v", context);
        //       BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
        //     },error: (e){
        //       ToastUtils.show("$e", context);
        //     });
        //   }else if(type == "11"){
        //     LoadingApi.func(UserRepository().getWinningReward(), context,complete: (v){
        //       ToastUtils.show("$v", context);
        //       BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
        //     },error: (e){
        //       ToastUtils.show("$e", context);
        //     });
        //   }else if(type == "12"){
        //     LoadingApi.func(UserRepository().getWeekReward(), context,complete: (v){
        //       ToastUtils.show("$v", context);
        //       BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
        //     },error: (e){
        //       ToastUtils.show("$e", context);
        //     });
        //   }



          // NavigatorUtil.navigateToPage(context, RewardVideoPage(type: type,)).then((value){
          //   if(value != null && value != "" && value != "null"){
          //     ToastUtils.show("$value", context);
          //     BlocProvider.of<TeamInfoBloc>(ctx).add(HttpEvent());
          //   }
          // });
        // })
      ],
    );
  }


  Widget _buildTopView(String title, String value) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(title, style: TextStyle(fontSize: 14, color: HexColor("#FEC8C8"))),
        SizedBox(height: 2,),
        Text(value, style: TextStyle(fontSize: 15, color: Colors.white)),
      ],
    );
  }
}



class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;
  StickyTabBarDelegate({@required this.child});
  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: HexColor("#F8F8F8"),
      child: this.child,
    );
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}